<template>
  <Combination
    ref="comSharePriceRef"
    class="price-udp"
    :items="comItem"
    :comData="ruleForm.data"
    :rules="comRules"
    :size="maxSize"
  ></Combination>
</template>

<script lang="ts" setup name="share-price">
import { FormRules } from 'element-plus';
import Combination from '@/components/combination/combination.vue';
import { IS_DECIMAL_4 } from '@/utils/verify';

const comSharePriceRef = ref();

let optionsS = reactive({
  org: [] as any,
});
let maxSize = ref(1);

const ruleForm = reactive({
  data: [] as any,
});

const comItem = reactive([
  {
    comName: 'select',
    labelWidth: 0,
    prop: 'operatorId',
    width: 219,
    isOnly: true,
    props: {
      prepend: '参与分润方',
      options: optionsS.org,
    },
  },
  {
    comName: 'input',
    labelWidth: 0,
    prop: 'shareMoney',
    width: 300,
    props: {
      prepend: '分润金额',
      append: '元/度',
      maxlength: 10,
      placeholder: '请输入分润金额，精确到4位小数',
    },
  },
]);

const comRules = reactive<FormRules>({
  operatorId: [
    {
      required: true,
      message: '请选择参与分润方',
      trigger: ['blur', 'change'],
    },
  ],
  shareMoney: [
    { required: true, message: '请输入分润金额', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_4,
      message: '请输入正确的分润金额，精确到4位小数',
      trigger: 'blur',
    },
  ],
});

const getOrgData = (arr: any) => {
  optionsS.org = [...arr];
  comItem[0].props.options = [...arr];
  nextTick(() => {
    comSharePriceRef.value?.setOptions(0, 0, optionsS.org);
    comSharePriceRef.value?.setItemDatas(optionsS.org);
  });
  maxSize.value = arr.length;
};

const getData = async () => {
  if (!comSharePriceRef.value) return;
  try {
    await Promise.all([comSharePriceRef.value.validate()]);
  } catch (fields: any) {
    for (const key in fields) {
      if (fields[key]) {
        comSharePriceRef.value.scrollToField(key);
        break;
      }
    }
    return false;
  }

  const data = comSharePriceRef.value?.getData();
  return data;
};

const setData = (data: any, arr: any) => {
  ruleForm.data = [];
  data.forEach((item: any, index: number) => {
    if (index === 0) {
      getOrgData(arr);
    } else {
      nextTick(() => {
        comSharePriceRef.value?.setOptions(index, 0, arr);
      });
    }
    ruleForm.data.push({
      operatorId: Number(item.operatorId),
      shareMoney: String(item.shareMoney),
    });
  });
};
defineExpose({
  getOrgData,
  getData,
  setData,
});
</script>

<style lang="scss" scoped>
:deep(.item-wrap) {
  margin-bottom: 18px;
}
</style>